import UIKit

extension UIColor {
    static func fromHex(_ hex: String) -> UIColor {
        // 移除 # 前缀和空白字符
        var hex = hex.trimmingCharacters(in: .whitespacesAndNewlines)
        if hex.hasPrefix("#") {
            hex = String(hex.dropFirst())
        }
        
        // 验证十六进制字符串长度
        guard hex.count == 3 || hex.count == 6 || hex.count == 8 else {
            return .clear
        }
        
        // 将 3 位 RGB 转换为 6 位
        if hex.count == 3 {
            let r = hex[hex.startIndex]
            let g = hex[hex.index(hex.startIndex, offsetBy: 1)]
            let b = hex[hex.index(hex.startIndex, offsetBy: 2)]
            hex = "\(r)\(r)\(g)\(g)\(b)\(b)"
        }
        
        // 转换为整数
        guard let intValue = UInt64(hex, radix: 16) else {
            return .clear
        }
        
        // 解析颜色值
        let a, r, g, b: UInt64
        if hex.count == 8 {
            r = (intValue >> 24) & 0xFF
            g = (intValue >> 16) & 0xFF
            b = (intValue >> 8) & 0xFF
            a = intValue & 0xFF
        } else {
            r = (intValue >> 16) & 0xFF
            g = (intValue >> 8) & 0xFF
            b = intValue & 0xFF
            a = 255
        }
        
        return UIColor(
            red: CGFloat(r) / 255.0,
            green: CGFloat(g) / 255.0,
            blue: CGFloat(b) / 255.0,
            alpha: CGFloat(a) / 255.0
        )
    }
} 